<template>
  <div class="found">
    <el-tabs v-model="activeTab" @tab-change="handleTabChange" class="product-tabs">
      <el-tab-pane label="关注" name="关注"></el-tab-pane>
      <el-tab-pane label="推荐" name="推荐"></el-tab-pane>
      <el-tab-pane label="国家补贴" name="国家补贴"></el-tab-pane>
      <el-tab-pane label="美食" name="美食"></el-tab-pane>
      <el-tab-pane label="科技" name="科技"></el-tab-pane>
      <el-tab-pane label="穿搭" name="穿搭"></el-tab-pane>
      <el-tab-pane label="运动" name="运动"></el-tab-pane>
      <el-tab-pane label="户外" name="户外"></el-tab-pane>
      <el-tab-pane label="护肤" name="护肤"></el-tab-pane>
    </el-tabs>

    <div class="product-list" v-loading="loading">
      <ProductCard v-for="product in products" :key="product.id" :product="product" @imageLoad="handleImageLoad" />
    </div>

    <!-- 加载动画 -->
    <div v-if="isFetching" class="loading-animation">
      <span class="spinner"></span>
      <p>加载中...</p>
    </div>

    <div v-if="loading" class="loading">加载中...</div>
    <div v-if="!hasMore" class="no-more">没有更多数据了</div>
    <!-- 新增的下一页按钮 -->
    <div v-if="hasMore" class="next-page-button">
      <el-button @click="fetchProducts" :loading="loading">下一页</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'
import ProductCard from '@/components/ProductCard.vue'
import { getProductsByPageDTO } from '@/api/product'
import { ProductType } from '@/type/product'

// 商品列表数据
const products = ref<any>([])

// 图片加载计数
const loadedImagesCount = ref(0)
const totalImages = ref(0)

// 修改handleImageLoad方法
const handleImageLoad = () => {
  loadedImagesCount.value++
  if (loadedImagesCount.value === totalImages.value) {
    // 图片加载完成后不需要手动计算布局，Grid会自动处理
  }
}

const activeTab = ref('推荐')
const currentPage = ref(1)
const pageSize = ref(10)
const loading = ref(false)
const hasMore = ref(true) // 是否还有更多数据

// 控制加载动画的显示
const isFetching = ref(false)

// 保存.el-main元素的引用
const elMainRef = ref<HTMLElement | null>(null)

const fetchProducts = async () => {
  if (loading.value || !hasMore.value) {
    console.log('阻止加载：loading =', loading.value, 'hasMore =', hasMore.value)
    return
  }

  console.log('开始加载数据...')

  try {
    loading.value = true
    isFetching.value = true // 显示加载动画

    // 根据当前页码和每页大小计算正确的起始位置
    const params = {
      tags: [activeTab.value], // 改为tags数组
      page: currentPage.value,
      pageSize: pageSize.value
    }

    console.log('请求参数：', params)

    const { list, total: totalCount } = await getProductsByPageDTO(params)

    console.log('收到响应：', { list, totalCount })

    if (list.length === 0) {
      console.log('没有更多数据')
      hasMore.value = false
      return
    }

    products.value = [...products.value, ...list]
    currentPage.value++

    // 如果当前加载的数据总量达到总数，则不再加载
    if (products.value.length >= totalCount) {
      console.log('达到数据总量，不再加载')
      hasMore.value = false
    }

    // 在数据加载完成后更新图片计数
    totalImages.value = products.value.length
    loadedImagesCount.value = 0

    console.log('数据加载完成')
  } catch (error) {
    console.error('数据加载失败：', error)
    hasMore.value = false
  } finally {
    loading.value = false
    isFetching.value = false // 隐藏加载动画
    console.log('加载完成')
  }
}

const handleTabChange = () => {
  currentPage.value = 1
  products.value = []
  hasMore.value = true
  fetchProducts()
}

// 防抖函数
function debounce(func: Function, delay: number) {
  let timer: ReturnType<typeof setTimeout>
  return function (this: Window, ...args: any[]) {
    clearTimeout(timer)
    timer = setTimeout(() => {
      func.apply(this, args)
    }, delay)
  }
}

// 滚动事件处理
const handleScroll = debounce(() => {
  if (!elMainRef.value) return
  
  const { scrollTop, scrollHeight, clientHeight } = elMainRef.value
  // 当滚动到底部附近时加载更多
  if (scrollTop + clientHeight >= scrollHeight - 10 && !loading.value) {
    pageSize.value = 10 // 后续每次加载10条数据
    fetchProducts()
  }
}, 200)

// 在组件挂载时获取产品数据并设置图片加载监听
onMounted(() => {
  fetchProducts()
  // 获取.el-main元素并添加滚动事件监听
  elMainRef.value = document.querySelector('.el-main')
  if (elMainRef.value) {
    elMainRef.value.addEventListener('scroll', handleScroll)
  }
})

onBeforeUnmount(() => {
  // 移除滚动事件监听
  if (elMainRef.value) {
    elMainRef.value.removeEventListener('scroll', handleScroll)
  }
})
</script>

<style scoped>
.product-tabs {
  margin: 0 30px;
}

.product-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(228px, 1fr));
  /* 自适应列数，每列最小宽度为220px */
  gap: 15px;
  /* 卡片之间的间距 */
  margin-top: 10px;
  padding: 0 30px;
}

.product-card {
  width: 100%;
  /* 宽度适应网格单元格 */
  /* 高度由内容决定 */
}

.loading,
.no-more {
  text-align: center;
  padding: 10px;
  color: #888;
}

/* 加载动画样式 */
.loading-animation {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 50px;
  margin: 20px 0;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.spinner {
  display: inline-block;
  width: 24px;
  height: 24px;
  border: 3px solid rgba(0, 0, 0, 0.1);
  border-radius: 50%;
  border-top-color: #333;
  animation: spin 1s ease-in-out infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.next-page-button {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
}
</style>